<?php

/**
 * [WeEngine System] Copyright (c) 2014 WE7.CC
 * WeEngine is NOT a free software, it under the license terms, visited http://www.we7.cc/ for more details.
 */
defined('IN_IA') or exit('Access Denied');

$dos = ['oauth_login_url', 'oauth_accesstoken', 'oauth_userinfo'];

$do = in_array($do, $dos) ? $do : '';
if (is_error(cloud_prepare())) {
	exit('service is unavailable.');
}
if (empty($_GPC['data'])) {
	iajax(-1, '获取请求data参数为空。');
}
$console_data = __secure_decode($_GPC['data']);
$console_data = iunserializer($console_data);
if (empty($console_data)) {
	iajax(-1, 'data参数有效性验证失败，请联系管理员处理。');
}
if ('oauth_login_url' == $do) {
	$login_url = url('user/login', ['referer' => $console_data['redirect_uri'], 'w7_oauth_login' => STATUS_ON], true);
	iajax(0, $login_url);
}

if ('oauth_accesstoken' == $do) {
	$cache_key = cache_system_key('console_oauth_code', ['code' => $console_data['code']]);
	$cache = cache_load($cache_key);
	if (empty($cache)) {
		iajax(-1, 'code不存在或已被使用');
	}
	$access_token = aes_encode(complex_authkey() . $console_data['code'] . $cache, $_W['setting']['site']['token'], $_W['setting']['site']['key']);
	$data = [
		'user_id' => $cache,
		'client_id' => $_W['setting']['site']['key'],
		'access_token' => $access_token,
		'expires_in' => (TIMESTAMP + 2 * CACHE_EXPIRE_LONG),
		'scope' => 'user',
	];
	pdo_delete('oauth_access_token', ['user_id' => $cache]);
	pdo_insert('oauth_access_token', $data);
	cache_delete($cache_key);
	iajax(0, $access_token);
}

if ('oauth_userinfo' == $do) {
	$access_token_info = pdo_get('oauth_access_token', ['access_token' => $console_data['access_token']]);
	if (empty($access_token_info)) {
		iajax(-1, '不存在的accesstoken');
	}
	if ($access_token_info['expires_in'] < TIMESTAMP) {
		iajax(-1, '过期的accesstoken');
	}
	$user_info = user_single($access_token_info['user_id']);
	if (empty($user_info)) {
		iajax(-1, '用户已不存在，请联系管理员确认');
	}
	$user_info['role_identify'] = user_is_founder($user_info['uid'], true) ? ACCOUNT_MANAGE_NAME_FOUNDER : (user_is_vice_founder($user_info['uid']) ? ACCOUNT_MANAGE_NAME_VICE_FOUNDER_RULE : ACCOUNT_MANAGE_NAME_GENERAL_RULE);
	$user_info['openid'] = md5($user_info['uid'] . $_W['setting']['site']['token'] . $_W['setting']['site']['key'] . $_W['config']['setting']['authkey']);
	iajax(0, $user_info);
}
